import { getUserInfo, updateUser } from '../../common/api'
const app = getApp();
Page({
  data: {
    userInfo: {
      avatarUrl: '',
      oldAvatarUrl: '',
      customerId: '',
      depositNum: '',
      mobile: '',
      nickName: '',
      waterNum: ''
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getUserInfo()
  },
  // 最终提交保存
  async tapSave() {
    console.log(this.data.userInfo);
    wx.showLoading({
      title: '修改中',
      mask: true,
    })
    // return
    let data = {
      "avatarUrl": this.data.userInfo.avatarUrl,
      "nickName": this.data.userInfo.nickName,
    }
    updateUser(data).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.removeStorageSync('userInfo')
        wx.setStorageSync("userInfo", data)
        wx.switchTab({ url: '/pages/wode/index' });
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: "获取信息失败",
        icon: 'error'
      })
    })
  },
  // 输入昵称
  onInput(e) {
    const { value } = e.detail
    console.log('输入昵称', value);
    this.setData({
      ['userInfo.nickName']: value
    })
  },
  // 选择头像
  onChooseAvatar(e) {
    console.log('选择头像', e);
    const { avatarUrl } = e.detail
    this.setData({
      ['userInfo.avatarUrl']: avatarUrl
    })
  },
  uploadFile() {
    if (this.data.oldAvatarUrl == this.data.userInfo.avatarUrl) {
      this.tapSave()
      return;
    }
    let that = this
    let file = {
      path: this.data.userInfo.avatarUrl,
      filename: "avatar.jpeg"
    };
    app.upload(file, null).then(res => {
      // 回传文件ID
      if (res.code == 200) {
        console.log('成功');
        that.setData({
          ['userInfo.avatarUrl']: res.data.fileUrl
        })
      }
      this.tapSave()
    }, err => {
      wx.hideLoading();
      wx.showModal({
        title: "提示",
        content: err.msg,
        mask: 1000
      })
    })
  },
  async getUserInfo() {
    wx.showLoading({
      title: '获取数据中...',
      mask: true,
    })
    getUserInfo(null).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        wx.removeStorageSync('userInfo')
        wx.setStorageSync("userInfo", res.data)
        console.log('个人信息', res);

        this.setData({
          userInfo: res.data || {},
          oldAvatarUrl: res.data.avatarUrl
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: "获取信息失败",
        icon: 'error'
      })
    })
  }
})
